﻿using System;
using System.Windows;
using System.Windows.Input;
using System.Windows.Navigation;
using CodeBadger.GasMileage.ViewModels;

namespace CodeBadger.GasMileage.Views
{
    public partial class AddEditPage
    {
        private AddEditViewModel Vm
        {
            get { return DataContext as AddEditViewModel; }
        }

        public AddEditPage()
        {
            InitializeComponent();
            InitializeViewModel();
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);
            TryLoadExistingNotebook();
            HideDeleteButtonIfNewEntry();
        }

        private void HideDeleteButtonIfNewEntry()
        {
            if (Vm.Entry.Id == Guid.Empty && ApplicationBar.Buttons.Count == 2)
            {
                ApplicationBar.Buttons.RemoveAt(1);
            }
        }

        private void TryLoadExistingNotebook()
        {
            string guid;
            if (!NavigationContext.QueryString.TryGetValue("id", out guid)) return;
            Vm.LoadById(new Guid(guid));
        }

        private void InitializeViewModel()
        {
            var vm = new AddEditViewModel();
            DataContext = vm;
        }

        private void DoneButtonClick(object sender, RoutedEventArgs e)
        {
            Vm.Save();
            NavigateToList();
        }

        private void ListClick(object sender, EventArgs e)
        {
            NavigateToList();
        }

        private void DeleteClick(object sender, EventArgs e)
        {
            var answer = MessageBox.Show("Delete this entry?", "", MessageBoxButton.OKCancel);
            if (answer != MessageBoxResult.OK) return;
            Vm.Delete();
            NavigateToList();
        }

        private void MileageTextBoxKeyUp(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter) GallonsTextBox.Focus();
        }

        private void GallonsTextBoxKeyUp(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter) PriceTextBox.Focus();
        }

        private void PriceTextBoxKeyUp(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter) DoneButton.Focus();
        }

        private void NavigateToList()
        {
            NavigationService.Navigate(new Uri("/Views/ListPage.xaml", UriKind.Relative));    
        }
    }
}